package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.dto.UserStatisticsDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Elora
 * @date 2025/7/18
 **/
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 统计指定时间区间内的营业额数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        // 一次性查询整个日期范围的数据
        LocalDateTime startDateTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endDateTime = LocalDateTime.of(end, LocalTime.MAX);

        //用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)){
            //计算指定日期的后一天
            begin = begin.plusDays(1);
            dateList.add(begin);
        }


        List<Map<String, Object>> dailyData = orderMapper.getDailyTurnover(startDateTime, endDateTime, Orders.COMPLETED);

        // 将查询结果转换为日期->营业额的Map
        Map<LocalDate, Double> turnoverMap = dailyData.stream()
                .collect(Collectors.toMap(
                        map -> ((java.sql.Date) map.get("orderDate")).toLocalDate(),
                        map -> Optional.ofNullable(map.get("dailySum"))
                                .map(sum -> ((Number) sum).doubleValue())
                                .orElse(0.0)
                ));


        // 构建每日营业额列表
        List<Double> turnoverList = dateList.stream()
                .map(date -> turnoverMap.getOrDefault(date, 0.0))
                .collect(Collectors.toList());

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }


    /**
     * 统计指定时间区间内的用户数量
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 生成日期列表
        List<LocalDate> dateList = new ArrayList<>();
        LocalDate temp = begin;
        while (!temp.isAfter(end)) {
            dateList.add(temp);
            temp = temp.plusDays(1);
        }

        // 一次性查询所有数据
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("begin", begin);
        queryMap.put("end", end);
        List<UserStatisticsDTO> userDataList = userMapper.getDailyUserStats(queryMap);

        // 转换为日期->数据的映射便于查找
        Map<LocalDate, UserStatisticsDTO> resultMap = userDataList.stream()
                .collect(Collectors.toMap(
                        UserStatisticsDTO::getDate,
                        dto -> dto,
                        (existing, replacement) -> existing)
                );

        // 构建结果列表
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        //int cumulativeTotal = 0;

        for (LocalDate date : dateList) {
            UserStatisticsDTO dto = resultMap.get(date);
            if (dto != null) {
                //cumulativeTotal += dto.getNewCount(); // 累计新增用户
                newUserList.add(dto.getNewCount());
                totalUserList.add(dto.getTotalCount());
            } else {
                // 当天没有数据
                newUserList.add(0);
                totalUserList.add(0);
            }
        }

        return UserReportVO.builder()
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .dateList(dateList.stream().map(LocalDate::toString).collect(Collectors.joining(",")))
                .build();
    }

    /**
     * 统计指定时间区间内的订单数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        // 生成日期列表
        List<LocalDate> dateList = new ArrayList<>();
        LocalDate temp = begin;
        while (!temp.isAfter(end)) {
            dateList.add(temp);
            temp = temp.plusDays(1);
        }

        LocalDateTime startDateTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endDateTime = LocalDateTime.of(end, LocalTime.MAX);

        //查询每天的订单总数
        List<Map<String, Object>> dailyData = orderMapper.getDailyOrder(startDateTime, endDateTime, null);

        // 将查询结果转换为日期->订单总数的Map
        Map<LocalDate, Integer> allOrderMap = dailyData.stream()
                .collect(Collectors.toMap(
                        map -> ((java.sql.Date) map.get("orderDate")).toLocalDate(),
                        map -> Optional.ofNullable(map.get("ordersNum"))
                                .map(sum -> ((Number) sum).intValue())
                                .orElse(0)
                ));


        // 构建每日订单总数列表
        List<Integer> allOrderList = dateList.stream()
                .map(date -> allOrderMap.getOrDefault(date, 0))
                .collect(Collectors.toList());

        //计算总日期范围内所有订单的量
        int totalOrders = allOrderList.stream().mapToInt(Integer::intValue).sum();


        //查询每天的有效(已完成)订单总数
        List<Map<String, Object>> dailyComplData = orderMapper.getDailyOrder(startDateTime, endDateTime, Orders.COMPLETED);

        // 将查询结果转换为日期->订单总数的Map
        Map<LocalDate, Integer> complOrderMap = dailyComplData.stream()
                .collect(Collectors.toMap(
                        map -> ((java.sql.Date) map.get("orderDate")).toLocalDate(),
                        map -> Optional.ofNullable(map.get("ordersNum"))
                                .map(sum -> ((Number) sum).intValue())
                                .orElse(0)
                ));


        // 构建每日有效订单总数列表
        List<Integer> complOrderList = dateList.stream()
                .map(date -> complOrderMap.getOrDefault(date, 0))
                .collect(Collectors.toList());
        //计算总日期范围内所有有效订单量
        int totalCompletedOrders = complOrderList.stream().mapToInt(Integer::intValue).sum();


        return OrderReportVO.builder()
                .orderCountList(StringUtils.join(allOrderList, ","))
                .validOrderCountList(StringUtils.join(complOrderList, ","))
                .dateList(StringUtils.join(dateList, ","))
                .totalOrderCount(totalOrders)
                .validOrderCount(totalCompletedOrders)
                .orderCompletionRate((double)totalCompletedOrders / totalOrders)
                .build();
    }

    /**
     * 统计指定时间区间内的销量排名前10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        // 调用Mapper查询指定时间区间内的销量前10的商品
        List<GoodsSalesDTO> top10List = orderMapper.getSalesTop10(begin, end);

        //把List集合封装成所需的VO对象
        List<String> nameList = top10List.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String names = StringUtils.join(nameList, ",");
        List<Integer> numberList = top10List.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numbers = StringUtils.join(numberList, ",");

        return SalesTop10ReportVO.builder()
               .nameList(names)
               .numberList(numbers)
               .build();
    }


    /**
     * 导出运营数据excel报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1. 查询数据库，获取最近30天的概览营业数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

        //2. 通过POI将查询到的营业数据写入到excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        //基于模版文件创建一个新的excel文件
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据--时间区间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);
            //填充数据--营业额
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            //填充数据--订单完成率
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //填充数据--新增用户数
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            //填充数据--有效订单
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            //填充数据--平均客单价
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
           for(int i = 0; i < 30; i++){
               LocalDate date = begin.plusDays(i);
               //查询某一天的营业数据
               BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

               //获取某一行
               XSSFRow row = sheet.getRow(7 + i);
               row.getCell(1).setCellValue(date.toString());
               row.getCell(2).setCellValue(data.getTurnover());
               row.getCell(3).setCellValue(data.getValidOrderCount());
               row.getCell(4).setCellValue(data.getOrderCompletionRate());
               row.getCell(5).setCellValue(data.getUnitPrice());
               row.getCell(6).setCellValue(data.getNewUsers());
           }


            //3. 通过输出流将excel文件下载给客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            //关闭资源
            outputStream.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
